import React, {useEffect, useState} from 'react';
import {Button, Form, Input, Modal, Table, TableProps} from 'antd';
import type {Room} from "@/types/resp/room";
import roomApi from '@/api/roomApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import BuildingSelector from "@/pages/building/BuildingSelector.tsx";


interface RoomSelectorProps {
  visible: boolean;
  onRoomSelected: (selectedRoom: { roomId?: number; residentRoomId?: number; roomNumber?: string; residentRoomNumber?: string; }) => void;
  onCloseRoomSelector: () => void;
}

const RoomSelector: React.FC<RoomSelectorProps> = ({visible, onRoomSelected, onCloseRoomSelector}) => {

  const [roomSelectorForm] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    roomSelectorForm.resetFields();
  };

  const [data, setData] = useState<Room[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<Room>> = await roomApi.find(roomSelectorForm.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<Room> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<Room>['columns'] = [
    {title: '楼栋名称', dataIndex: 'buildingName', key: 'buildingName'},
    {title: '房号', dataIndex: 'roomNumber', key: 'roomNumber'},
    {title: '所在楼层', dataIndex: 'floorNumber', key: 'floorNumber'},
    {title: '建筑面积', dataIndex: 'grossFloorArea', key: 'grossFloorArea'},
    {title: '实用面积', dataIndex: 'netFloorArea', key: 'netFloorArea'},
  ];

  const handleRowDoubleClick = (row: Room) => {
    onRoomSelected({
      roomId: row.id,
      residentRoomId: row.id,
      roomNumber: row.roomNumber,
      residentRoomNumber: row.roomNumber,
    })
  };

  const selectorFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onCloseRoomSelector}>关闭</Button>
    </div>
  );

  useEffect(() => {
    if (visible) {
      onSearch();
    }
  }, [visible]);

  const [buildingSelectorVisible, setBuildingSelectorVisible] = useState(false);
  const findBuilding = () => {
    setBuildingSelectorVisible(true);
  }
  const handleBuildingSelected = (selectedBuilding: { buildingId?: number; buildingName?: string; }) => {
    setBuildingSelectorVisible(false)
    if (selectedBuilding && 'buildingId' in selectedBuilding) {
      roomSelectorForm.setFieldsValue(Object.assign(roomSelectorForm.getFieldsValue(), {
      buildingId: selectedBuilding['buildingId'],
      buildingName: selectedBuilding['buildingName'],
      }));
    }
  };
  const handleCloseBuildingSelector = () => {
    setBuildingSelectorVisible(false)
  };

  return (
    <Modal title={"单元信息选择器(双击行选中)"} open={visible} onCancel={onCloseRoomSelector}
        width={'var(--modal-width)'} footer={selectorFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      <Form form={roomSelectorForm} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="buildingName" label="楼栋名称">
          <Input.Search placeholder="请选择楼栋名称" onSearch={findBuilding} readOnly={true} />
        </Form.Item>
        <Form.Item name="roomNumber" label="房号">
          <Input maxLength={32} placeholder="请输入房号"/>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
      </Form>
      <Table<Room> columns={columns} dataSource={data} size="small" rowKey={record => record.id}
                         pagination={{ position: ["bottomCenter"] }}
                         onRow={(row) => ({
                           onDoubleClick: (event) => {
                             event.preventDefault();
                             handleRowDoubleClick(row);
                           },
                         })}/>
      <BuildingSelector visible={buildingSelectorVisible} onBuildingSelected={handleBuildingSelected} onCloseBuildingSelector={handleCloseBuildingSelector} />
    </Modal>
  );
};

export default RoomSelector;
